﻿// Copyright (c) Appeon. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

using System;
using System.Collections.Generic;

namespace SnapObjects.Data.DB2
{
    internal class DB2ProcedureParameterSchemaProvider : DB2RoutineParameterSchemaProvider
    {
        private readonly string _sqlText = @"
SELECT procs.procedure_id as object_uniqueidentifier,
       parms.parmname as parameter_name, 
       parms.typename as parameter_datatype,
       parms.parm_mode as parameter_mode,
       parms.length as parameter_precision,
       parms.scale as parameter_scale,
       null as parameter_defaultvalue,
       parms.length as parameter_size
  FROM syscat.procedures procs 
  LEFT JOIN syscat.procparms parms
    ON procs.specificname=parms.specificname and procs.procname=parms.procname
 WHERE {0}
 ORDER BY parms.ORDINAL";

        public DB2ProcedureParameterSchemaProvider(DataContext dataContext) : base(dataContext)
        {
        }

        protected override bool IsProcedure => true;

        protected override ProcedureSchema CreateParameterSchema(
            string name, IReadOnlyList<AdoDbParameter> adoDbParameters, IReadOnlyList<DynamicModel> dbParameters)
        {
            return new ProcedureSchema(name, adoDbParameters);
        }

        protected override string GetQueryString(RoutineNameInfo nameInfo, ISqlGenerationHelper helper)
        {
            var procName = helper.RemoveDelimitIdentifier(nameInfo.Name);

            var condition = $"upper(procs.procname)=upper('{procName}')";

            if (!String.IsNullOrWhiteSpace(nameInfo.Schema))
            {
                var schema = helper.RemoveDelimitIdentifier(nameInfo.Schema);

                condition = $"{condition} and upper(procs.procschema)=upper('{schema}')";
            }
            else
            {
                condition = $"{condition} and procs.procschema=current_schema";
            }

            return String.Format(_sqlText, condition);
        }
    }
}
